<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<%--
  Created by IntelliJ IDEA.
  User: CM
  Date: 2017/6/20
  Time: 上午12:30
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>商品订单管理</title>
    <link href="${ctx}/resources/pagination/style/pagination.css" rel="stylesheet" type="text/css">
    <link href="${ctx}/resources/pagination/style/common.css" rel="stylesheet" type="text/css">
    <jsp:include page="../../common/header.jsp"></jsp:include>
    <jsp:include page="../../common/cloud-head.jsp"></jsp:include>
    <jsp:include page="../../common/dt.jsp"></jsp:include>
    <script type="text/javascript" src="${ctx}/resources/pagination/script/jquery.pagination.js"></script>
    <style>
        .good-info-item-box{
            max-width:18rem;
            text-align: center;
            padding:0.4rem 0.8rem;
            overflow:hidden;
            cursor: pointer;
            transition:all ease .8s;
        }

        .good-info-item-box:hover{
            background:#cfcfcf;
            padding:0.6rem 1rem;
        }

        .good-info-item-box img{
            max-width:100%;
            height:auto;
        }

        .good-info-item-box p{
            color:#383838;
        }
    </style>
</head>
<body>

<div class="col-md-12">
    <div class="card">
        <div class="card-action">
            条件查询
        </div>
        <div class="card-content">
            <div class="col-md-12" style="text-align:right;">
                <button class="btn btn-primary" onclick="loadData()" style="margin-right:2rem;"><i
                        class="fa fa-search"></i>搜索
                </button>
                <input type="hidden" value="1" name="pageNum" id="pageNum"/>
                <input type="hidden" value="5" name="pageSize" id="pageSize"/>
                <input type="hidden" value="" name="total" id="total"/>
            </div>
            <div class="clear"></div>
            <div class="col-md-12">
                <div class="col-md-4">
                    <label>手机号 <shiro:hasAnyRoles name="all">/店铺</shiro:hasAnyRoles></label>
                    <input type="text" id="phone" name="phone" placeholder="输入手机号码查询"/>
                    <shiro:hasAnyRoles name="all">

                        <select class="chosen" data-placeholder="选择店铺" id="shop" name="shop">
                            <option value="">全部</option>
                        </select>
                    </shiro:hasAnyRoles>
                </div>
                <div class="col-md-4">
                    <label>时间/类别</label>
                    <input type="datetime" placeholder="点击选择时间" id="timeRange" name="startTime"/>
                    <select name="status" id="status">
                        <option value="">全部</option>
                        <option value="WAIT_EDIT_PRICE">提交待改价</option>
                        <option value="UNPAID">待支付</option>
                        <option value="PAYMENT_SUCCESS">支付成功</option>
                        <option value="PAYMENT_FAIL">支付失败</option>
                        <option value="PAYMENT_TIMEOUT">支付超时</option>
                        <option value="DELIVERED">已发货</option>
                        <option value="RECED_CONFIRMATION">已收货</option>
                        <option value="ORDER_CANCEL">订单取消</option>
                        <option value="ORDER_REFUND">申请退款</option>
                        <option value="ORDER_REFUNDED">退款申请已处理</option>
                    </select>
                </div>
                <div class="col-md-4">
                    <label>订单金额</label>
                    <input type="number" placeholder="输入最小金额" value="" id="minAmount" name="minAmount"/>
                    <input type="number" placeholder="输入总金额" value="" id="maxAmount" name="maxAmount"/>
                </div>
            </div>
            <div class="clear"></div>
        </div>
    </div>
</div>
<div class="col-md-12">
    <div class="card">
        <div class="card-action">
            订单列表(Tip:金额栏数据格式表示：实际支付金额／订单总金额)
        </div>
        <div class="card-content">
            <div>
                <table id="mainTable" cellpadding="0" cellspacing="0" border="0" class="auto-table">
                    <thead>
                    <tr>
                        <%--<th>订单编号</th>--%>
                        <th>商家</th>
                        <th>用户手机</th>
                        <th>商品信息</th>
                        <th>订单总额/商品数量</th>
                        <th>订单状态</th>
                        <th>运费方案</th>
                        <th>下单时间</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody>

                    </tbody>
                </table>
                <div class="pagination pagination-right pagination-small" id="pagination">

                </div>
            </div>
        </div>
    </div>
</div>

<script type="text/html" id="dataTmpl">
    <tr>
        <%--<td>\${id}</td>--%>
        <td>
            <span class="shop-info-load" data-id="\${shopId}"><i class="fa fa-spin fa-spinner"></i> Loading...</span>
        </td>
        <td>\${receivePhone}</td>
        <td>
            <span class="good-info-load" data-id="\${goodId}"><i class="fa fa-spin fa-spinner"></i> Loading...</span>
        </td>
        <td><span style="min-width:4rem;display:inline-block;">\${sumPrice||'0.00'}</span> (商品数量:\${goodNum})</td>
        <td>\${getStatusDesc(status)}{{if status == 'DELIVERED'}}[物流单号:\${expressNo}]{{/if}}</td>
        <td><span class="express-loading" data-id="\${expressId || ''}"><i
                class="fa fa-spin fa-spinner"></i> Loading</span></td>
        <td>\${formatDate(createTime)}</td>
        <td>
            <div>
                {{if status == 'WAIT_EDIT_PRICE'}}
                <button class="btn btn-warning" onclick="modifyPrice('\${id}')">修改金额</button>
                {{/if}}
                {{if status == 'UNPAID' || status == 'WAIT_EDIT_PRICE'}}
                <button class="btn btn-error" onclick="cancelOrder('\${id}')">取消订单</button>
                {{/if}}
                {{if status == 'PAYMENT_SUCCESS'}}

                <button class="btn btn-success" onclick="postOrder('\${id}')">确认发货</button>
                {{if refundStatus == 1 }}
                    <div style="margin: 0.8rem auto;">
                        <button class="btn btn-success" onclick="refund('\${id}',2)">同意退款</button>
                        <button class="btn btn-danger" onclick="refund('\${id}',3)">拒绝退款</button>
                    </div>
                {{/if}}

                {{if refundStatus == 2}}
                <div style="margin: 0.8rem auto;">
                    <strong>该订单已经退款：\${refundAmount}</strong>
                </div>
                {{/if}}
                {{if refundStatus == 3}}
                <div style="margin: 0.8rem auto;">
                    <strong>退款申请已驳回</strong>
                </div>
                {{/if}}
                {{/if}}
            </div>
        </td>
    </tr>
</script>
<script type="text/html" id="goodPreviewTmpl">
    <%--onclick="showGoodPreviewDetail('\${str}') title="点击查看商品信息""--%>
    <div class="good-info-item-box"  >
        <img src="\${img[0]}"/>
        {{if sale_price == 0}}
        <p>\${goodName}</p>
        <span style="color:red;font-size:12px;">议价商品</span>
        {{else}}
        <p>\${goodName}</p>
        <span style="color:red;font-size:12px;">￥ \${sale_price} / \${source_price} </span>
        {{/if}}
    </div>
</script>

<script type="text/html" id="goodPreviewDetailTmpl">
<div>
    <p>这里是商品的详细信息，通过弹窗的方式来展示</p>
    <div>\${goodName}</div>
</div>
</script>
<script>
    $(function () {
        <shiro:hasAnyRoles name="all">

        loadShop();
        </shiro:hasAnyRoles>
        loadData();
    })

    function showGoodPreviewDetail(dataStr){
        var data = JSON.parse(dataStr);


        var html = $("#goodPreviewDetailTmpl").tmpl(data).html();

        bootbox.alert({
            title:'商品详细信息',
            message:html
        });
    }


    var STATUS = null;
    function loadData() {
        var data = {
            phone: $("#phone").val() || "",
            shopId: $("#shop").val() || "",
            startTime: $("#timeRange").val() ? $("#timeRange").val().split(" to ")[0] : "",
            endTime: $("#timeRange").val() ? $("#timeRange").val().split(" to ")[1] : "",
            minAmount: $("#minAmount").val() || "",
            maxAmount: $("#maxAmount").val() || "",
            targetShop: $("#shopId").val() || "",
            pageNum: $("#pageNum").val() || 1,
            pageSize: $("#pageSize").val() || 10,
            status: $("#status").val() || ""
        };
        asyncAjax({
            url: ctx + "/order/list?" + $.param(data).replace(/(%5D|%5B)/g, ""),
            success: function (res) {
                //console.log("res:%o", res);
                if (res["result"] == "0") {
                    STATUS = res["statusDesc"];
                    $("#total").val(res["total"]);
                    $("#mainTable tbody").html("");
                    $("#dataTmpl").tmpl(res["data"]).appendTo($("#mainTable tbody"));
                    pageLoad();
                    fillGoodInfo();
                    fillShopInfo();
                    loadExpress();
                } else {
                    bootbox.alert(res["msg"]);
                }
            }
        })
    }

    function loadExpress() {
        $(".express-loading").each(function (idx, el) {
            var expressId = $(this).attr("data-id");
            if (!isEmpty(expressId)) {
                $.post(ctx + '/express/one?expressId=' + expressId, function (res) {
                    if (res.result == "0") {
                        $(el).html(res["data"]["name"] || "未知物流方式");
                    }
                })
            }else{
                $(el).html("<font color=\"#8b0000\">该订单未选择物流信息</font>")
            }
        })
    }

    function getStatusDesc(status) {
        return STATUS[status];
    }

    function fillGoodInfo() {
        $(".good-info-load").each(function (idx, el) {
            loadGoodInfo($(this).attr("data-id"), this);
        })
    }

    function fillShopInfo() {
        $(".shop-info-load").each(function (idx, el) {
            loadShopInfo($(this).attr("data-id"), el);
        })
    }

    function pageLoad() {
        var pageCount = Math.ceil((parseInt(($('#total').val() || 0)) / parseInt($("#pageSize").val() || 10)));
        $("#pagination").pagination({
            pageCount: pageCount,
            pageSize: parseInt($("#pageSize").val() || 10),
            totalCount: parseInt($("#total").val()),
            current: parseInt($("#pageNum").val()),
            jump: true,
            coping: true,
            homePage: '首页',
            endPage: '末页',
            prevContent: '上页',
            nextContent: '下页',
            callback: function (that) {
                //console.log("that:%o", that);
                $("#pageNum").val(that.getCurrent());
                loadData();
                that.setCurrentPage()
            }
        })
    }

    function loadGoodInfo(id, el) {
        var data = {goodId: id};
        asyncAjax({
            url: ctx + "/goodMgr/good/info?" + $.param(data).replace(/(%5D|%5B)/g, ""),
            success: function (res) {
                //console.log("res:%o", res);
                if (res["result"] == "0") {
                    $(el).html("");
                    res["data"]["str"] = $.toJSONString(res["data"]);
                    $("#goodPreviewTmpl").tmpl(res["data"]).appendTo($(el));

                } else {
                    $(el).html('<font color="red">' + res["msg"] + '</font>')
                }
            }
        })
    }

    function loadShopInfo(id, el) {
        var data = {};
        asyncAjax({
            url: ctx + "/user/mgr/user/" + id + "?" + $.param(data).replace(/(%5D|%5B)/g, ""),
            success: function (res) {
                //console.log("res:%o", res);
                if (res["result"] == "0") {
                    $(el).html(res["data"]["nickname"]);
                } else {
                    $(el).html(res["msg"])
                }
            }
        })
    }

    function modifyPrice(orderId) {
        bootbox.confirm({
            title: '修改订单价格',
            message: '<div class="form-group"><label>订单价格</label><input type="number" value="" name="priceModifyValue" id="priceModifyValue"/></div>'
            + '<div class="form-group"><label>修改备注</label><input type="text" value="" name="priceModifyRemarks" id="priceModifyRemarks"/></div>'
            + '<div>Tip:为了方便订单信息核对，请在修改订单价格的同时务必填写订单修改备注</div>',
            callback: function (res) {
                if (res == true) {
                    var price = $("#priceModifyValue").val();
                    var remarks = $("#priceModifyRemarks").val();
                    if (isEmpty(price) || parseFloat(price) < 0) {
                        bootbox.alert("订单金额不能为空，也不能填负数哦~");
                        return;
                    }
                    if (isEmpty(remarks)) {
                        bootbox.alert("为了方便订单信息核对，请在修改订单价格的同时务必填写订单修改备注");
                        return;
                    }
                    var data = {
                        sumPrice: price,
                        remarks: encodeURI(remarks),
                        orderId: orderId
                    };
                    asyncAjax({
                        url: ctx + "/order/modify/price?" + $.param(data).replace(/(%5D|%5B)/g, ""),
                        success: function (res) {
                            //console.log("res:%o", res);
                            if (res["result"] == "0") {
                                bootbox.alert("修改成功，请提示客户及时支付!");
                                loadData();
                            } else {
                                bootbox.alert(res["msg"]);
                            }
                        }
                    })


                } else {
                    bootbox.alert("用户取消");
                }
            },
            buttons: {
                confirm: {
                    label: '确定'
                },
                cancel: {
                    label: '取消'
                }
            }
        })
    }

    function cancelOrder(id) {
        var data = {orderId: id};
        asyncAjax({
            url: ctx + "/order/cancel?" + $.param(data).replace(/(%5D|%5B)/g, ""),
            success: function (res) {
                //console.log("res:%o", res);
                if (res["result"] == "0") {
                    bootbox.alert("取消成功!");
                    loadData();
                } else {
                    bootbox.alert(res["msg"]);
                }
            }
        })
    }

    function postOrder(id) {
        bootbox.confirm({
            title: '商品发货请填入物流单号',
            message: '<div><label>物流单号</label><input type="text" value="" id="expressNo" plcaeholder="请填入物流单号" /></div><div class="clear"></div><p>Tip:发货请无比填入物流单号，以方便物流信息查询核对！</p>',
            buttons: {
                confirm: {
                    label: '确定'
                },
                cancel: {
                    label: '取消'
                }
            },
            callback: function (res) {
                if (res == false) {
                    bootbox.alert("操作取消成功！");
                } else {
                    var expressNo = $("#expressNo").val();
                    if (isEmpty(expressNo)) {
                        bootbox.alert("物流单号不能为空!");
                        return;
                    }
                    var data = {orderId: id, expressNo: expressNo};
                    asyncAjax({
                        url: ctx + "/order/post?" + $.param(data).replace(/(%5D|%5B)/g, ""),
                        success: function (res) {
                            //console.log("res:%o", res);
                            if (res["result"] == "0") {
                                bootbox.alert("操作成功!");
                                loadData();
                            } else {
                                bootbox.alert(res["msg"]);
                            }
                        }
                    })
                }
            }
        })

    }


    function refund(orderId,refundStatus){
        if(refundStatus == 2){
            bootbox.confirm({
                title:'拒绝退款原因',
                message:'<div class="form-group"><label>拒绝原因</label><input type="text" name="rreason" id="rreason" value="" placeholder="请填入退款原因"/> </div>',
                callback:function(res){
                    if(res == true){
                        var data ={
                            orderId:orderId,
                            refundStatus:refundStatus,
                            reason:$("#rreason").val()||""
                        };
                        asyncAjax({
                            url: ctx + "/order/refunds/deal?" + $.param(data).replace(/(%5D|%5B)/g, ""),
                            success: function (res) {
                                //console.log("res:%o", res);
                                if (res["result"] == "0") {
                                    bootbox.alert("操作成功");
                                    loadData();
                                } else {

                                }
                            }
                        })
                    }
                }
            })
        }else{
            var data ={
                orderId:orderId,
                refundStatus:refundStatus,
                reason:"同意"
            };
            asyncAjax({
                url: ctx + "/order/refunds/deal?" + $.param(data).replace(/(%5D|%5B)/g, ""),
                success: function (res) {
                    //console.log("res:%o", res);
                    if (res["result"] == "0") {
                        bootbox.alert("操作成功");
                        loadData();
                    } else {

                    }
                }
            })
        }
    }
    <shiro:hasAnyRoles name="all">
    function loadShop() {
        var data = {reviewStatus: 2};
        asyncAjax({
            url: ctx + "/user/mgr/list/3?" + $.param(data).replace(/(%5D|%5B)/g, ""),
            success: function (res) {
                //console.log("res:%o", res);
                if (res["result"] == "0") {
                    $.each(res["data"], function (idx, shopUser) {
                        $("#shop").append("<option value='" + shopUser.id + "'>" + shopUser.nickname + "</option>");
                    })
                    $("#shop").chosen({width: 380});
                } else {
                    bootbox.alert(res["msg"]);
                }
            }
        })
    }
    </shiro:hasAnyRoles>
</script>
</body>
</html>
